<?php
class FileUpload{
	/*Singleton{{{*/
	public static function getInstance(){
		static $instance=null;
		if($instance===null){ 
			$instance = new self();
		}
		return $instance;
	}
	private function __construct(){}
	private function __clone(){
		trigger_error("Clone is not allowed.", E_USER_ERROR);
	}
	/*}}}*/

	private $file_ext;
	private $max_filesize=false;
	private $target_path='upload/';
	private $allow=false;
	private $deny=false;
	private $file;

	public function __set($name,$value){
		$this->name = $value;
	}
	public function __get($name){
		return $this->name;
	}

	// Check the ext
	private function check_ext(){
		if(is_array($this->deny)){
			if(in_array($this->file_ext,$this->deny))
				return false;
			else 
				return true;
		}
		if(is_array($this->allow)){
			if(in_array($this->file_ext,$this->allow)){
				move_uploaded_file($this->file['tmp_name'], $this->target_path.$this->file['name']);
				return true;
			}else
				return false;
		}
	}

	public function upload_file($file){
		$thumb = Core::getInstance()->sys_load_class('Thumb');
		$width = isset($_POST['width'])?intval($_POST['width']):200;
		$height = isset($_POST['height'])?intval($_POST['height']):200;
		if(is_array($file)){
			$num = count($file['name']);
			$db_uploadfile=array();
			$db_original_uploadfile=array();
			$db_thumb_uploadfile=array();
			for($i=0;$i<$num;$i++){
				if(empty($file['name'][$i])) continue;

				$tmp = explode('.',$file['name'][$i]);
				$this->file_ext = end($tmp);
				if(!$this->check_ext()) $file['error'][$i] = 'The filename is not allowed!';
				$filename= md5(uniqid(rand(), true));
				$db_uploadfile[] = $filename.'.'.$this->file_ext;
				$db_original_uploadfile[] = $file['name'][$i];
				$db_thumb_uploadfile[] = 'thumb_'.$filename.'.'.$this->file_ext;
				// 新文件
				move_uploaded_file($file['tmp_name'][$i], $this->target_path.$filename.'.'.$this->file_ext);
				// 对应缩略图
				$thumb->resizeImg($this->target_path.$filename.'.'.$this->file_ext,$this->target_path.'thumb_'.$filename.'.'.$this->file_ext,$width,$height);
			}
			return array('original_uploadfile'=>$db_original_uploadfile,'uploadfile'=>$db_uploadfile,'thumb_uploadfile'=>$db_thumb_uploadfile);
		}else{
			$this->file = $file;
			$tmp = explode('.',$this->file['name']);
			$this->file_ext = end($tmp);
			if(!$this->check_ext()) $this->file['error'] = 'The filename is not allowed!';
			if($this->file['error'] !== 0) return false;
			$filename= $this->target_path.md5(uniqid(rand(), true)).$this->file_ext;
			move_uploaded_file($this->file['tmp_name'], $filename);
		}
		return true;
	}

}
